//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Diagnostics.Contracts;
using OpenLS.Spreadsheet.Expressions;

namespace OpenLS.Spreadsheet.Formats.Biff.Tokens
{
    class NotSupportedFormulaException: ApplicationException
    {
        
    }
    internal sealed class NameXToken : FormulaToken
    {
        private readonly AccessorType _type;
        private ushort _ixti;
        private uint _nameIndex;

        public NameXToken(AccessorType type)
        {
            _type = type;
        }

        public NameXToken(AccessorType type, ushort ixti, uint nameIndex)
        {
            Contract.Requires(nameIndex > 0);
            _type = type;
            _ixti = ixti;
            _nameIndex = nameIndex;
        }


        public override ushort GetLength(FormulaReadContextType formulaReadContextType)
        {
            return 6;
        }

        private uint NameId
        {
            get { return _nameIndex; }
        }

        internal override void ReadContent(FormulaReadContext  context)
        {
            _ixti= context.ReadUInt16();
            _nameIndex= context.ReadUInt32();
        }

        public override void WriteContent(FormulaWriteContext context)
        {
            context.WriteUInt16(_ixti);
            context.WriteUInt32(_nameIndex);
        }

        public override FormulaTokenId TokenId
        {
            get {
                switch (_type)
                {
                    case AccessorType.Array:
                        return FormulaTokenId.NameXA;
                        case AccessorType.Reference:
                        return FormulaTokenId.NameX;
                        case AccessorType.Value:
                        return FormulaTokenId.NameXV;
                        default:throw new NotSupportedException();
                } }
        }

        public string GetDefinedName (BiffReaderWorkbookContext context)
        {
            return context.GetExternalDefinedName(_ixti, (int) (NameId - 1));
        }

        internal override Expression GetExpression(FormulaEvaluationContext context)
        {
            string nn = GetDefinedName(context.WorkbookContext);
           return new NameExpression(context.Workbook, nn); //\\to fix for worksheet
        }
    }
}